package vip.xiaomoli.courier.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import vip.xiaomoli.courier.component.timewheel.CourierTimeWheel;
import vip.xiaomoli.courier.dao.CourierDao;

import javax.sql.DataSource;

@Configuration
@EnableConfigurationProperties(CourierConfigurationProperties.class)
public class CourierAutoConfiguration {

    @Value("classpath:sql/CourierInit.sql")
    private Resource courierInitSql;

    @Bean
    public DataSourceInitializer dataSourceInitializer(DataSource dataSource) {
        DataSourceInitializer initializer = new DataSourceInitializer();
        initializer.setDataSource(dataSource);
        ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        populator.addScripts(courierInitSql);
        initializer.setDatabasePopulator(populator);
        return initializer;
    }

    @Bean
    public CourierDao courierDao(DataSource dataSource) {
        return new CourierDao(dataSource);
    }

    @Bean
    public CourierTimeWheel timeWheel() {
        return new CourierTimeWheel();
    }

}
